import 'package:flutter/material.dart';

import 'dart:io';
import 'package:dio/dio.dart';
import 'dart:convert';

import 'package:chewie/chewie.dart';
import 'package:chewie/src/chewie_player.dart';
import 'package:video_player/video_player.dart';

// 横屏和竖屏
import 'package:flutter/services.dart';
import 'package:orientation/orientation.dart';

class videoChewiePreview extends StatefulWidget {
  @override
  _VideoAppState createState() => _VideoAppState();
}

class _VideoAppState extends State<videoChewiePreview> {
  var currentCaption,
      captionList,
      videoUrl,
      responseData,
      currentPosition,
      currentPositionArr,
      currentPositionTime;

  VideoPlayerController _videoPlayerController;
  ChewieController _chewieController;

  var dio = Dio();
  Response response;

  getFodderNew() async {
    try {
      response = await dio.get(
        "https://www.bettermorph.com/micoservcice/user/homework/getFodderNew?fodderId=06e77a6ed534432eaa6ea4721330f978&type=1&userId=602598&betterStatus=0&taskId=2c9f808c6cd7e8b9016cfb0bcfb60e19",
      );

      print('response.data');
      print(response.data);

      responseData = response.data;
      if (response.statusCode == 200) {
        setState(() {
          videoUrl = responseData['obj']['videoUrl'];
          captionList = responseData['obj']['caption'];
        });

        _videoPlayerController = VideoPlayerController.network(videoUrl)
          // 播放状态
          ..addListener(() {
            final bool isPlaying = _videoPlayerController.value.isPlaying;
            if (isPlaying != '_isPlaying') {
             // print('播放中。。。');
              currentPositionArr =
                  _videoPlayerController.value.position.toString().split(':');
              //                    double.parse(
              //                        currentPositionArr[currentPositionArr.length - 1]
              //                            .substring(2, 5)

              if (double.parse(currentPositionArr[1]) > 0) {
                print('超过一分钟');
                currentPositionTime = double.parse(currentPositionArr[1]) * 60 +
                    double.parse(
                        currentPositionArr[currentPositionArr.length - 1]
                            .substring(0, 2));
              } else {
                currentPositionTime = double.parse(
                    currentPositionArr[currentPositionArr.length - 1]
                        .substring(0, 2));
              }

//              print('currentPositionTime');
//              print(currentPositionTime);
//              print('currentPosition');
//              print(_videoPlayerController.value.position);

              captionList.forEach((item) {
                if (double.parse(item['beginTime'].split('.')[0]) ==
                    currentPositionTime) {
                  // print(item);
                  setState(() {
                    currentCaption = item['engContent'];
                  });
                }
              });
            }
          });

        _chewieController = ChewieController(
          videoPlayerController: _videoPlayerController,
          aspectRatio: 3 / 2,
          autoPlay: true,
          looping: false,
          // Try playing around with some of these other options:
        );
      }
    } catch (e) {
      print(e);
    }
  }

  @override
  void initState() {
    super.initState();

    getFodderNew();

    OrientationPlugin.forceOrientation(DeviceOrientation.landscapeLeft);

    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: Center(
        child: new Stack(children: <Widget>[
          _chewieController != null
              ? AspectRatio(
                  aspectRatio: 3 / 2,
                  child: Chewie(
                    controller: _chewieController,
                  ),
                )
              : Center(
                  child: new Image.asset("assets/images/loading.gif"),
                ),
          _chewieController != null && currentCaption != null
              ? new Positioned(
                  left: 35.0,
                  right: 35.0,
                  bottom: 45.0,
                  child: new Text(
                    currentCaption,
                    textAlign: TextAlign.center,
                    style: new TextStyle(
                      color: Colors.black,
                      fontSize: 20.0,
                      fontFamily: 'serif',
                      shadows: <Shadow>[
                        Shadow(color: Colors.pink, offset: Offset(1, 1))
                      ],
                    ),
                  ),
                )
              : Container()
        ]),
      ),

//      floatingActionButton: FloatingActionButton(
//        onPressed: () {
//          setState(() {
//            _controller.value.isPlaying
//                ? _controller.pause()
//                : _controller.play();
//          });
//        },
//        child: Icon(
//          _controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
//        ),
//      ),
    );
  }

  @override
  void dispose() {
    super.dispose();

    _videoPlayerController.dispose();
    _chewieController.dispose();

    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);
    OrientationPlugin.forceOrientation(DeviceOrientation.portraitUp);
  }
}
